package com.tr.rentcar.controller.home;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tr.rentcar.model.bean.User;
import com.tr.rentcar.model.bean.UserDiscount;
import com.tr.rentcar.model.dao.DiscountDao;
import com.tr.rentcar.model.dao.UserDiscountDao;

/**
 * Servlet implementation class DiscountController
 * 点击领取优惠券
 */
@WebServlet("/ddiscount")
public class DiscountController extends HttpServlet {
	DiscountDao dd = new DiscountDao();
	UserDiscountDao udd = new UserDiscountDao();
	UserDiscount ud;
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		Integer did = Integer.parseInt(request.getParameter("id") + "");
		Integer num = Integer.parseInt(request.getParameter("num"));
		//获取登录用户的id
		User user = (User) request.getSession().getAttribute("userinfo");
		if(user!=null){
			Integer uid=user.getUid();
			Integer dnum = num - 1;
			try {
				if (udd.didAndUid(did, user.getUid()) == null) {
					dd.updatebyid(dnum, did);//更新优惠券数量
					udd.saveDiscount(uid, did);//插入到该用户拥有的优惠券中
					out.println("已领取");
				}
				else {
					out.println("您已领取");
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
